/**
 * Created by wenguangjia on 2017/9/19.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('fileNameSearchController', fileNameSearchController)
    fileNameSearchController.$inject = ['$scope', '$rootScope', '$state', 'searchService', '$localStorage'];
    function fileNameSearchController($scope, $rootScope, $state, searchService, $localStorage) {
        $scope.partition = '所有';
        $scope.param = {
            file_name: null,
            startTime: getToday00Clock(),
            endTime: getToday11Clock(),
            dateValue: null,
            dateType: "second",
            queryType: "0",
            partition: null,
            area: null
        };
        $scope.isQuickQuery = true;
        $scope.queryData = {true: "精确查找", false: "快速查找"};
        var requestData = "";//requeste参数
        $scope.selectQuery = function () {
            $scope.param.startTime = null;
            $scope.param.queryType == "0" ? $scope.isQuickQuery = true : $scope.isQuickQuery = false;
        };
        $scope.query = function () {
            requestData = generate();
            $scope.ELKGridOptions.dataSource.read();
        };

        //生成参数格式
        function generate() {
            var data = {
                "query": {
                    "bool": {
                        "must": [],
                        "filter": []
                    }
                },
                "size": 0,
                "aggs": {
                    "byFileName": {
                        "terms": {
                            "field": "file_name",
                            "size": 100
                        },
                        "aggs": {
                            "topHit": {
                                "top_hits": {
                                    "sort": [
                                        {
                                            "@timestamp": {
                                                "order": "desc"
                                            }
                                        }
                                    ],
                                    "size": 1
                                }
                            }
                        }
                    }
                }
            };

            var obj = data['query']['bool'];
            if ($scope.param.partition != undefined && $scope.param.partition != null && $scope.param.partition != "") {
                var arrayObj = {"term": {"partition": $scope.param.partition}};
                obj.filter.push(arrayObj);
            }
            if ($scope.param.file_name != null && $scope.param.file_name != "") {
                var arrayObj = {"wildcard": {"file_name": ($scope.param.file_name + '*')}};
                obj.filter.push(arrayObj);
            }
            if ($scope.isQuickQuery) {
                if ($scope.param.startTime != null && $scope.param.endTime == null) {
                    var arrayObj = {"range": {"@timestamp": {"gte": $scope.param.startTime}}};
                    obj.filter.push(arrayObj);
                } else if ($scope.param.startTime == null && $scope.param.endTime != null) {
                    var arrayObj = {"range": {"@timestamp": {"lt": $scope.param.endTime}}};
                    obj.filter.push(arrayObj);
                } else if ($scope.param.startTime != null && $scope.param.endTime != null) {
                    var arrayObj = {
                        "range": {
                            "@timestamp": {
                                "gte": $scope.param.startTime,
                                "lt": $scope.param.endTime
                            }
                        }
                    };
                    obj.filter.push(arrayObj);
                }
            } else {
                $scope.param.endTime = new Date();
                if ($scope.param.dateValue != null && $scope.param.dateValue != "") {
                    if ($scope.param.dateType == "second") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setSeconds($scope.param.startTime.getSeconds() - $scope.param.dateValue);
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "minute") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setMinutes($scope.param.startTime.getMinutes() - $scope.param.dateValue);
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "hour") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours() - $scope.param.dateValue);
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "day") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours() - ($scope.param.dateValue * 24));
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "week") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours() - ($scope.param.dateValue * 24 * 7));
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "month") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setMonth($scope.param.startTime.getMonth() - $scope.param.dateValue);
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    } else if ($scope.param.dateType == "year") {
                        $scope.param.startTime = new Date();
                        $scope.param.startTime.setFullYear($scope.param.startTime.getFullYear() - $scope.param.dateValue);
                        var arrayObj = {
                            "range": {
                                "@timestamp": {
                                    "gte": $scope.param.startTime,
                                    "lt": $scope.param.endTime
                                }
                            }
                        };
                        obj.filter.push(arrayObj);
                    }
                } else {
                    var arrayObj = {"range": {"@timestamp": {"lt": $scope.param.endTime}}};
                    obj.filter.push(arrayObj);
                }
            }

            return data;
        }

        /**
         * grid
         * @type {*[]}
         */

        var columns = [
            {field: "partition", title: "分区", width: "80px"},
            {field: "timestamp", title: "生成时间", format: "{0: yyyy-MM-dd HH:mm:ss:fff}", width: "180px"
            },
            {field: "file_name", title: "文件名", width: "280px", attributes: {style: 'white-space: nowrap '}},
            {field: "host", hidden: true},
            {field: "logtime", hidden: true},
            {field: "flag", hidden: true},
            // {field: "key1", title: "关键字1", width: "100px",attributes: {style: 'white-space: nowrap '}},
            // {field: "key2", title: "关键字2", width: "100px", hidden: true},
            // {field: "key3", title: "关键字3", width: "100px", hidden: true},
            // {field: "key4", title: "关键字4", width: "100px", hidden: true},
            // {field: "key5", title: "关键字5", width: "100px", hidden: true},
            // {field: "priority", title: "级别", width: "80px", values: prioritys, hidden: true},
            // {field: "category", title: "类别", width: "150px", hidden: true},
            // {field: "interval", title: "间隔时间", width: "150px", hidden: true},
            // {field: "pid", title: "进程号", width: "150px", hidden: true},
            // {field: "ip", title: "IP地址", width: "150px", hidden: true},
            // {field: "mac", title: "MAC地址", width: "150px", hidden: true},
            // {field: "username", title: "用户名", width: "100px"},
            // {field: "formname", title: "画面名", width: "100px"},
            // {
            //     field: "svc", title: "服务名", width: "110px"
            // },
            // {field: "func", title: "函数名", width: "110px", hidden: true},
            {
                field: "command", title: "查询", width: "120px",
                template: function (dataItem) {
                    var result = '<a target="_blank" ng-click="setObj(dataItem)">查询日志</a>'
                    return result;
                }
            },
            {
                field: "download", title: "原文操作", width: "120px",
                template: function (dataItem) {
                    var result =  '<a kendo-tooltip k-content="\'打开原文\'" class="open-text" ng-click="click(dataItem,0)"></a>' +
                        '<a kendo-tooltip k-content="\'下载原文\'" class="download-text" ng-click="click(dataItem,1)"></a>';
                    return result;
                }
            }
        ];


        $scope.click = function (dataItem, action) {
            var hostname = dataItem.host;
            dataItem.fileName = dataItem.file_name;
            if (action === 0) {
                searchService.getPartitionIp2Host({host: hostname}).then(
                    function (resp) {
                        if (resp.data.length > 0) {
                            var ip = resp.data[0].ip;

                            var address = generrateDownAddress(dataItem, ip);
                            // action == 0 ? openTrace(address) : downTrace(address);
                            openTrace(address);
                        }
                    }, function (error) {
                        console.log(error);
                    }
                );
            }

            if (action === 1) {
                var downloadAddress = "api/partitionip2host/trace?hostName="+ hostname + "&fileName="
                    + dataItem.fileName + "&logTime=" + dataItem.logtime;
                var a = document.createElement('a');
                a.href = downloadAddress;
                a.download = "";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        };

        function openTrace(address) {
            if (browserType() == 'Safari') {
                var a = document.createElement('a');
                a.href = address;
                a.click();
            } else {
                window.open(address);
            }
        }

        function downTrace(address) {
            if (browserType() == 'Safari') {
                var a = document.createElement('a');
                a.href = address;
                a.click();
            } else if (browserType() == 'IE') {
                window.open(address);
            } else {
                var a = document.createElement('a');
                a.href = address;
                a.download = "";
                a.click();
            }
        }

        $scope.setObj = function (dataItem) {
            dataItem.fileName = dataItem.file_name;
            dataItem.searchType = 3;

            var params = {
                searchType: dataItem.searchType,
                flag: dataItem.flag,
                fileName: dataItem.fileName,
                partition: dataItem.partition,
                id: dataItem.sourceId,
                "@timestamp": dataItem["@timestamp"]
            };

            var url = $state.href('svcconsole',{completelyLog:JSON.stringify(params)});
            window.open(url,'_blank');
        };

        $scope.ELKGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu: true
        };
        $scope.ELKModel = kendo.data.Model.define({
            id: "sourceId",
            fields: {
                timestamp: {validation: {required: true}, type: 'date'}
            }
        });
        $scope.ELKGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    searchService.query(requestData, $scope.param.area, 'service').then(function (resp) {
                        console.log(resp);
                        var gridData = [];
                        var data = resp.data.aggregations.byFileName.buckets;
                        angular.forEach(data, function (item) {
                            var host = "";
                            item.topHit.hits.hits[0]._source.host ? host = item.topHit.hits.hits[0]._source.host : host = item.topHit.hits.hits[0]._source.beat.hostname;
                            var obj = {
                                file_name: item.key,
                                timestamp: item.topHit.hits.hits[0]._source['@timestamp'],
                                partition: item.topHit.hits.hits[0]._source.partition,
                                host: host,
                                logtime: item.topHit.hits.hits[0]._source.logtime,
                                flag:item.topHit.hits.hits[0]._source.flag
                            };
                            gridData.push(obj);
                        });
                        e.success(gridData);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (requestData == "") {
                    e.preventDefault();
                }
            },
            schema: {
                model: $scope.ELKModel
            }
        });

        /**
         * get partition
         * @type {string}
         */
        $scope.partition = '全部';
        var partitionSrc = "";
        searchService.getPartition({}).then(
            function (resp) {
                partitionSrc = resp.data;
                $scope.partitionSource = toTree(resp.data);
            }, function (err) {
            }
        );
        $scope.selectShow = function (item) {
            if (item == 0) {
                $scope.param.area = null;
                $scope.param.partition = null;
                $scope.partition = "全部";
            }
            angular.forEach(partitionSrc, function (k) {
                if (item.ename == k.ename) {
                    $scope.param.area = k.code;
                    $scope.param.partition = k.ename;
                    $scope.partition = item.fname + "-" + item.cname;
                }
            });
            $scope.win.close();
        };
    }

})();

